const fs = require('fs').promises; // 使用fs的promises API
const path = require('path');
const readline = require('readline');

const baseDirectory = process.argv[2];
const fileSuffixName = process.argv[3];

if (!baseDirectory || !fileSuffixName) {
    console.error('使用方法：node mergeCode.js [文件夹路径] [文件后缀名], 例如：node mergeCode.js D:/code/ java');
    process.exit(1); // 如果没有提供参数，退出程序
}

// 要合并的文件类型
const fileType = `.${fileSuffixName}`

async function main() {
    try {
        let filelists = await findFiles(baseDirectory);
        console.log(`共有${fileSuffixName}文件${filelists.length}个`);

        let totalLines = 0;
        const targetLines = 3000;
        let mergedContent = '';
        const outputFilePath = path.join('合并代码文件.txt'); // 定义输出文件的路径

        for (let file of filelists) {
            let fileContent = await readFile(file)
            const fileLines = fileContent.split('\n');
            if (totalLines < targetLines) {
                mergedContent += `${fileLines.join('\n')}`;
                totalLines += fileLines.length
            } else {
                break
            }
        }
        // 合并结束,写入文件并停止
        await writeFile(outputFilePath, mergedContent);
        console.log(`${totalLines}行合并完成，文件名：${outputFilePath}`);

    } catch (err) {
        console.error("在读取目录时发生错误:", err);
    }
}

main()


async function findFiles(baseDirectory) {
    let filelist = [];
    try {
        const files = await fs.readdir(baseDirectory, { withFileTypes: true });
        for (const file of files) {
            if (file.isDirectory()) {
                const subFiles = await findFiles(path.join(baseDirectory, file.name));
                filelist = filelist.concat(subFiles);
            } else if (path.extname(file.name) === fileType) {
                filelist.push(path.join(baseDirectory, file.name));
            }
        }
    } catch (err) {
        console.error(err);
        return [];
    }
    return filelist;
}


async function readFile(file) {
    let content = await fs.readFile(file, { encoding: 'utf8' });
    return content;
}

async function writeFile(file, content) {
    await fs.writeFile(file, content, 'utf8');
}
